const Sharerule = require('../model/sharerule');
const Sharedetail=require('../model/sharedetail')
const dateFormat = require('dateformat');


/**
 *  添加一条数据
 * @param {string} param.rule_name 规则名称
 * @param {string} param.description 规则描述
 * @param {number} param.share_number 分享人数
 * @param {number} param.state 被分享人的会员状态，，0，非会员,1,老会员，2，新会员
 * @param {string} param.start_date 开始时间
 * @param {string} param.end_date 结束时间
 */
exports.insertOne = async function (params) {
    try {

        let checkCount = await Sharerule.checkTimeInfo(params);
        if (checkCount != 0) {
            return { success: false, code: 10002, msg: "当前时间范围已存在分享规则" };
        }

        let data = await Sharerule.createOne(params);
        if (data != null) {
            return { success: true, code: 10000, msg: "新增成功" };
        } else {
            return { success: false, code: 10001, msg: "新增失败" };
        }

    } catch (e) {
        return { success: false, code: 10010, msg: e };
    }
}



/**
 * 根据id查询某条规则
 * @param {object} params 
 * @param {number} params.id 规则id
 * @returns {object} 查找的数据
 */
exports.findById = async function (param) {
    try {
        let data = await Sharerule.findById(params.id);
        return { success: true, code: 10000, msg: data }
    } catch (e) {
        return { success: false, code: 10010, msg: e };
    }
}


/**
 * 删除此条规则
 * @param {object} params
 * @param {number} params.id 规则id
 * @returns {Array} 操作结果
 */
exports.deleteById = async function (params) {
    try {
        console.log(params)
        let delRes = await Sharerule.deleteById(params);
        if (delRes.affectedRows == 1) {
            return { success: true, code: 10000, msg: "删除成功" };
        } else {
            return { success: false, code: 10001, msg: "删除失败" };
        }
    } catch (e) {
        return { success: false, code: 10010, msg: e };
    }
}


/**
 * 更新此条规则
 * @param {object} params.data
 * @param {number} params.id
 */
exports.updateOne = async function (params) {
    try {
        //查询分享规则是否存在
        let shareRule = await Sharerule.findAllById(params.id);
        if (shareRule == null || shareRule.length == 0) {
            return { success: false, code: 10001, msg: "规则不存在" };
        }

        params.data.gmt_modified = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");

        const updateRes = await Sharerule.updateOne(params);
        if (updateRes.affectedRows == 1) {

            return { success: true, code: 10000, msg: "修改成功" };
        } else {
            return { success: false, code: 10002, msg: "修改失败" };
        }
    } catch (e) {
        return { success: false, code: 10010, msg: e };
    }
}
